<%@page language="java" contentType="text/html; charset=UTF-8" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="html" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<html:header title="新增入库单">

    <link rel="stylesheet" href="${baseUrl}css/public.css" media="all">

    <style type="text/css">

        .layui-table-cell {            overflow: visible !important;        }
        /* 使得下拉框与单元格刚好合适 */
        td .layui-form-select{
            margin-top: -10px;
            margin-left: -15px;
            margin-right: -15px;
        }

        .save{
            cursor:pointer;
        }
    </style>

    <script>
        jQuery(function () {
            fixTableOperatorButton();
            $("#cancel").click(function () {
                closeSubIframe();
            });

            getByType("${baseUrl}",ORDER_TYPE.RKD.type, $("#no"));

            ajaxSelect("${baseUrl}user/user/getAll.action","userId");

        });

        layui.use(['form', 'table', 'laydate'], function () {
            let $ = layui.jquery,
                form = layui.form,
                table = layui.table,
                laydate = layui.laydate,
                util = layui.util;

            laydate.render({
                elem: '#date'
            });

            $("[name='date']").val(GMTToDate(new Date()));

            form.verify({
                userId: function(value, item){ //value：表单的值、item：表单的DOM对象
                    if(value == null || value==""){
                        return '经办人不能为空';
                    }
                },
                date: function(value, item){ //value：表单的值、item：表单的DOM对象
                    if(value == null || value==""){
                        return '业务日期不能为空';
                    }
                }
            });

            form.on('submit(save)',function (data) {
                let entity = data.field;
                delete entity.number;
                delete entity.linkUnit;
                delete entity.linkNo;
                delete entity.typeName;
                delete entity.house;
                entity.date = genDate(entity.date);
                //经货单商品
                let houseInGoodsVoList = [];
                let houseInPacketVoList = [];
                $.each(table.cache.table,function (i,d) {
                    if (!emptyEntity(d.goodsId)) {
                        let vo = {};
                        vo.houseWaitInGoodsId = d.houseWaitInGoodsId;
                        vo.inGoodsGoodsId = d.inGoodsGoodsId;
                        vo.refundGoodsId = d.refundGoodsId;
                        vo.goodsTransferGoodsId = d.goodsTransferGoodsId;
                        vo.borrowInGoodsId = d.borrowInGoodsId;
                        vo.borrowOutBackGoodsId = d.borrowOutBackGoodsId;
                        vo.goodsId = d.goodsId;
                        vo.unitId = d.unitId;
                        vo.times = d.times;
                        vo.number = d.number;
                        vo.remark = d.remark;
                        vo.goodsSnList = genUploadTableList(d.goodsSnList);
                        houseInGoodsVoList.push(vo);
                    } else {
                        let vo = {};
                        vo.houseWaitInPacketId = d.houseWaitInPacketId;
                        vo.refundPacketId = d.refundPacketId;
                        vo.packetId = d.packetId;
                        vo.packetName = d.name;
                        vo.packetNo = d.no;
                        vo.number = d.number;
                        vo.remark = d.remark;

                        let packetGoodsVoList = [];
                        $.each(d.packetGoodsVoList,function (i,pg) {
                            packetGoodsVoList.push({
                                packetId : pg.packetId,
                                goodsId : pg.goodsId,
                                unitId:pg.unitId,
                                times:pg.times,
                                number:pg.number,
                                price:pg.price,
                                amount:pg.amount,
                            });
                        });

                        vo.packetGoodsVoList = packetGoodsVoList;
                        houseInPacketVoList.push(vo);
                    }
                });

                entity.houseInGoodsVoList = houseInGoodsVoList;
                entity.houseInPacketVoList = houseInPacketVoList;

                console.log(JSON.stringify(entity));
                tipLoad("入库单新增中...");
                post("${baseUrl}house/houseIn/add.action", entity, function (res) {
                    closeAll();
                    if (res.code == 1) {
                        refreshHouseIn();
                        refreshHouseWaitIn();
                        refreshMainIframe("${baseUrl}house/houseWaitInDetail.action?id=${houseWaitInId}");
                        closeSubIframe();
                    } else {
                        errTip(res.msg);
                    }
                });
                return false;
            });

            $(".save").click(function () {
                if (table.cache.table.length == 0) {
                    errTip("未选择任何商品");
                    return false;
                }

                let tableData = table.cache.table;
                for (let i=0;i<tableData.length;i++) {
                    if (tableData[i].sn) {
                        if (tableData[i].goodsSnList == undefined || tableData[i].goodsSnList.length==0) {
                            errTip("商品("+tableData[i].name + ")的序列号数量不能为0");
                            return ;
                        } else if (tableData[i].goodsSnList.length > tableData[i].waitInNumber) {
                            errTip("商品("+tableData[i].name + ")的序列号数量不能大于待入库数量");
                            return ;
                        }
                    } else {
                        if (tableData[i].number == 0) {
                            errTip("商品("+tableData[i].name + ")的数量不能为0");
                            $("tr[data-index='"+i+"']").find(".number").css("border-color","red");
                            return ;
                        } else if (tableData[i].number > tableData[i].waitInNumber) {
                            errTip("商品("+tableData[i].name + ")的数量不能大于待入库数量");
                            $("tr[data-index='"+i+"']").find(".number").css("border-color","red");
                            return ;
                        }
                    }
                }

                let deliveryNo = $('[name="deliveryNo"]').val();
                if(!emptyEntity(deliveryNo) && !/^[A-Za-z0-9]+$/.test(deliveryNo)){
                    errTip('物流单号只能是数字和字母');
                    return;
                }

                $("[lay-filter='save']").click();

            });



            table.on('tool(table)', function (obj) {
                let data = obj.data;
                if (obj.event === 'delete') {
                    if (table.cache.table.length == 1) {
                        errTip("列表只有一行，不能被删除");
                        return;
                    }
                    operator_del(obj);
                }
            });

            get("${baseUrl}house/houseWaitIn/getVoById.action?id=${houseWaitInId}", function (res) {
                if (res.code == 1) {
                    $("[name='type']").val(res.data.type);
                    let linkOrder = genLinOrder(res.data);
                    if (linkOrder.linkUnit != "") {
                        $("#linkUnit").val(linkOrder.linkUnit.name);
                    } else {
                        $("#linkUnit").val("无");
                    }
                    $("#typeName").val(linkOrder.typeName);
                    $("#linkNo").html(linkOrder.linkNo);
                    $("#linkNo").attr("linkDetailUrl",linkOrder.linkDetailUrl);
                    $("#linkNo").attr("linkDetailTitle",linkOrder.linkDetailTitle);

                    $("#linkNo").unbind().bind('click',function () {
                        openTab($(this).attr("linkDetailTitle"), $(this).attr("linkDetailUrl"));
                    });

                    $("#house").val(res.data.houseVo.store.name + ">" + res.data.houseVo.name);

                    let list=[];
                    $.each(res.data.houseWaitInGoodsVoList, function (i,d) {
                        if (d.waitInNumber > 0) {
                            let vo = d.goodsId==null? d.packetVo:d.goodsVo;
                            vo.houseWaitInGoodsId = d.id;
                            vo.inGoodsGoodsId = d.inGoodsGoodsId;
                            vo.refundGoodsId = d.refundGoodsId;
                            vo.goodsTransferGoodsId = d.goodsTransferGoodsId;
                            vo.borrowInGoodsId = d.borrowInGoodsId;
                            vo.borrowOutBackGoodsId = d.borrowOutBackGoodsId;
                            vo.goodsId = d.goodsId;
                            vo.waitInNumber = d.waitInNumber;
                            vo.hasInNumber = d.hasInNumber;
                            vo.number = d.waitInNumber;
                            vo.unitId = d.unitId;
                            vo.times = d.times;
                            vo.remark = d.remark;
                            list.push(vo);
                        }
                    });

                    $.each(res.data.houseWaitInPacketVoList, function (i,d) {
                        if (d.waitInNumber > 0) {
                            let vo = d;
                            vo.houseWaitInPacketId = d.id;
                            vo.refundPacketId = d.refundPacketId;
                            vo.packetId = d.packetId;
                            vo.name = d.packetName;
                            vo.no = d.packetNo;
                            vo.waitInNumber = d.waitInNumber;
                            vo.hasInNumber = d.hasInNumber;
                            vo.number = d.waitInNumber;
                            vo.remark = d.remark;
                            list.push(vo);
                        }
                    });

                    renderTable(list);
                }else {
                    tip("获取订单信息失败");
                }
            });
        });




        function renderTable(list) {
            layui.table.render({
                id: 'table',
                elem: '#table',
                toolbar: '#tableToolBar',
                defaultToolbar:[],
                data: list,
                totalRow:true,
                text: {
                    none: '未选择商品' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
                },
                cols: [[
                    {type: 'numbers'},
                    {field: 'name', minWidth: 140, title: '名称/规格',style:"font-size:12px;",templet:'#nameBar'},
                    {field: 'no', width: 140, title: '商品编号', style: "font-size:12px;"},
                    {width: 120, title: '属性', style: "font-size:12px;", templet: function (d) {
                        return genAttr(d.attrNameVoList);
                    }},
                    {field:'number', width: 110, title: '数量',templet: "#numberBar"},
                    {width: 110, title: '序列号',templet: "#snNumberBar"},
                    {width: 120, title: '单位', style: "font-size:12px;", templet: function (d) {
                        return d.goodsId==null ? "": genUnitName(d.goodsUnitVoList,d.unitId);
                    }},
                    {title: '操作', minWidth: 70, fixed:'right', templet: '#operBar'},

                ]],
                limit: Number.MAX_VALUE,
                done: function (res, curr, count) {
                    ajaxSelect("${baseUrl}settAccount/settAccount/listVo.action","settAccountId");

                    $("[name='deliveryAmt']").val(getPrice(0));
                    $("[name='deliveryAmt']").unbind().bind('blur', function () {
                        let amt = genAmount($(this).val());
                        $(this).val(getPrice(amt));
                    });

                    $(".snNumberDiv").unbind().bind('click',function () {
                        let index = $(this).parents('tr').data('index');
                        let tableData = layui.table.cache.table;
                        showSnList(tableData[index].name, tableData[index].goodsSnList);
                    });

                    processTotalRow();

                    $(".packetName").unbind().bind('click',function () {
                        let index = $(this).parents('tr').data('index');
                        let tableData = layui.table.cache.table;
                        showPacketList(tableData[index].name, tableData[index].packetGoodsVoList);
                    });



                    $(".number").blur(function () {
                        let $input=$(this);
                        let number = genNumber($input.val());
                        checkNumber(number,$input);
                        processNumber(number, $input,true,true);
                        processTotalRow();
                    });

                    $(".numberSn").click(function () {
                        snIndex = $(this).parents('tr').data('index');
                        let goodsId = layui.table.cache.table[snIndex].goodsId;
                        let houseId = $("[name='houseId']").val();
                        if (houseId.length < 36 ) {
                            errTip("请选择仓库");
                            return;
                        }

                        let url = "";
                        if ($('[name="type"]').val() == "3") {
                            url = "${baseUrl}dialog/sn/goodsTransferSelect.action.action?goodsId="+goodsId+"&goodsTransferId="+$('[name="goodsTransferId"]').val();
                        } else {
                            url = "${baseUrl}dialog/sn/import.action.action?type=2&houseId="+houseId+"&goodsId="+goodsId;
                        }

                        openHtmlDialog("管理序列号",url, function (layero, index) {
                            var iframe = window[layero.find('iframe')[0]['name']];

                            let goodsSnList = layui.table.cache.table[snIndex].goodsSnList;
                            if (emptyList(goodsSnList)) {
                                goodsSnList=[];
                            }
                            iframe.setDataToTable(goodsSnList,genGoodsSnMap(layui.table.cache.table));
                        });
                    });
                }
            });
        }
        /**
         * 开启sn号的商品，会回调这个函数
         *
         */
        function processSnImport(data) {
            layui.table.cache.table[snIndex].number = data.length;
            layui.table.cache.table[snIndex].goodsSnList = data;
            let child = data.length + '个';
            $("tr[data-index='"+snIndex+"']").find(".snNumberDiv").html(child);
            $("tr[data-index='"+snIndex+"']").find(".number").html(data.length);

            processNumber(data.length, $("tr[data-index='"+snIndex+"']").find(".number"));
            processTotalRow();
            $(window).focus();
        }

        /**
         * 开启sn号的商品，会回调这个函数
         *
         */
        function processSnSelect(data) {
            layui.table.cache.table[snIndex].number = data.length;
            layui.table.cache.table[snIndex].goodsSnList = data;
            let child = data.length + '个';
            $("tr[data-index='"+snIndex+"']").find(".snNumberDiv").html(child);
            processNumber(data.length, $("tr[data-index='"+snIndex+"']").find(".number"));
            processTotalRow();
            $(window).focus();
        }

        function processTotalRow() {
            let number=0;
            $.each(layui.table.cache.table, function (i,d) {
                number += parseInt(d.number);
            });
            setTotalRow("number",number);
            setTotalRow("0","合计");
        }

        function checkNumber(number,$input) {
            let index = $input.parents('tr').data('index');
            let tableData = layui.table.cache.table;
            if (number == 0) {
                errTip("数量必须大于0");
                $input.css("border-color","red");
            } else if (tableData[index].waitInNumber < number) {
                errTip("数量不能大于待入库数量");
                $input.css("border-color","red");
            } else {
                $input.css("border-color","#ffffff");
            }
        }

        //获取关联单结构体
        function genLinOrder(d) {
            let vo = {};
            $("[name='houseId']").val(d.houseVo.id);

            if (d.type ==1) {
                vo = d.inGoodsVo;
                vo.linkUnit = d.inGoodsVo.provider;
                vo.typeName = '进货';
                vo.linkNo = d.inGoodsVo.no;
                vo.linkDetailUrl = "${baseUrl}inGoods/inGoodsDetail.action?id="+d.inGoodsVo.id;
                vo.linkDetailTitle = "进货单详情";


                $('[name="inGoodsId"]').val(d.inGoodsVo.id);
                return vo;
            }
            if (d.type ==2) {
                vo = d.refundVo;
                vo.linkUnit = d.refundVo.custom;
                vo.typeName = '销售退货';
                vo.linkNo = d.refundVo.no;
                vo.linkDetailUrl = "${baseUrl}sale/refundDetail.action?id="+d.refundVo.id;
                vo.linkDetailTitle = "销售退货单详情";


                $('[name="refundId"]').val(d.refundVo.id);
                return vo;
            }

            if (d.type ==3) {
                vo = d.goodsTransferVo;
                vo.linkUnit = "";
                vo.typeName = '调拨单';
                vo.linkNo = d.goodsTransferVo.no;
                vo.linkDetailUrl = "${baseUrl}house/goodsTransferDetail.action?id="+d.goodsTransferVo.id;
                vo.linkDetailTitle = "调拨单详情";
                $('[name="houseOutId"]').val(d.houseOutId);
                $('[name="goodsTransferId"]').val(d.goodsTransferVo.id);
                return vo;
            }
            if (d.type ==4) {
                vo = d.borrowInVo;
                vo.linkUnit = d.borrowInVo.provider;
                vo.typeName = '借入单';
                vo.linkNo = d.borrowInVo.no;
                vo.linkDetailUrl = "${baseUrl}house/borrowInDetail.action?id="+d.borrowInVo.id;
                vo.linkDetailTitle = "调拨单详情";
                $('[name="borrowInId"]').val(d.borrowInVo.id);
                return vo;
            }
            if (d.type ==5) {
                vo = d.borrowOutBackVo;
                vo.linkUnit = d.borrowOutBackVo.custom;
                vo.typeName = '借出归还';
                vo.linkNo = d.borrowOutBackVo.no;
                vo.linkDetailUrl = "${baseUrl}house/borrowOutBackDetail.action?id="+d.borrowOutBackVo.id;
                vo.linkDetailTitle = "调拨单详情";
                $('[name="borrowOutBackId"]').val(d.borrowOutBackVo.id);
                return vo;
            }
        }
    </script>

</html:header>

<body>

<div class="layui-inline" style="margin-bottom: 20px;">
    <a class="layui-btn layui-btn-primary" id="cancel">取消</a>
</div>
<div class="layuimini-container">
    <div class="layuimini-main">
        <form class="layui-form" action="" lay-filter="form">
            <button style="display: none;" lay-submit lay-filter="save" class="layui-btn">保存</button>
            <input type="hidden" name="close" value="false">
            <input type="hidden" name="houseWaitInId" value="${houseWaitInId}">
            <input type="hidden" name="houseId">
            <input type="hidden" name="type">
            <input type="hidden" name="houseOutId">
            <input type="hidden" name="inGoodsId">
            <input type="hidden" name="refundId">
            <input type="hidden" name="goodsTransferId">
            <input type="hidden" name="borrowInId">
            <input type="hidden" name="borrowOutBackId">


            <h2 class="tableBeforeTitle">入库单</h2>
            <div style="height: 4px;background-color: #bbbbbb;width: 100%;margin: 20px 0 2px 0;"></div>
            <div style="height: 1px;width: 100%;background-color: #dddddd;margin-bottom: 10px;"></div>
            <div style="height: 10px;"></div>

            <div class="layui-form-item">
                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">编号</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" id="no" name="no" class="layui-input readonly" readonly style="font-size: 12px;">
                    </div>
                </div>

                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">关联业务</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" id="typeName" name="typeName" class="layui-input readonly" readonly style="font-size: 12px;">
                    </div>
                </div>


                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">关联单号</div>
                    <div style="display: inline-block;width: 160px;">
                        <a href="#" id="linkNo"></a>
                    </div>
                </div>

                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">往来单位</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" id="linkUnit" name="linkUnit" class="layui-input readonly" readonly style="font-size: 12px;">
                    </div>
                </div>


                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">入库仓库</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" id="house" name="house" class="layui-input readonly" readonly style="font-size: 12px;">
                    </div>
                </div>

                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">业务日期</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" name="date" id="date" lay-verify="date" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">经手人</div>
                    <div style="display: inline-block;width: 160px;">
                        <select name="userId" lay-verify="userId" lay-filter="userId">
                        </select>
                    </div>
                </div>
            </div>

            <div style="clear:both;height: 10px;"></div>
            <table class="layui-hide" id="table" lay-filter="table" lay-size="sm"></table>


            <div style="overflow: auto;margin-top: -10px">
            <table class="layui-table" style="margin: 0px 0 0 0;min-width: 600px;">
                <colgroup>
                    <col>
                    <col width="300">
                </colgroup>
                <tbody>
                <tr>
                    <td>
                        <div style="position: relative;">
                            <input type="text" id="remark" name="remark" class="layui-input no-border" style="padding-left: 60px;">
                            <div style="position: absolute;top: 10px;left: 10px;">
                                备注:
                            </div>
                        </div>
                    </td>

                    <td class="save" style="background-color: #1E9FFF;color:#ffffff;text-align: center;font-size: 16px;">确认入库</td>
                </tr>
                </tbody>
            </table>
            </div>
        </form>
    </div>
</div>

</body>

<script type="text/html" id="tableToolBar">
    <div class="layui-inline" style="margin-bottom: 4px;">
        <div class="label">物流公司</div>
        <div style="display: inline-block;width: 160px;">
            <input type="text" name="deliveryOrg" class="layui-input" style="font-size: 12px;">
        </div>
    </div>

    <div class="layui-inline" style="margin-bottom: 4px;">
        <div class="label">物流单号</div>
        <div style="display: inline-block;width: 160px;">
            <input type="text" name="deliveryNo" lay-verify="deliveryNo" class="layui-input" style="font-size: 12px;">
        </div>
    </div>

    <div class="layui-inline" style="margin-bottom: 4px;">
        <div class="label">支付运费</div>
        <div style="display: inline-block;width: 160px;">
            <input type="text" name="deliveryAmt" class="layui-input" style="font-size: 12px;">
        </div>
    </div>
    <div class="layui-inline" style="margin-bottom: 4px;">
        <div class="label">支付账户</div>
        <div style="display: inline-block;width: 160px;">
            <select name="settAccountId">
            </select>
        </div>
    </div>
</script>

<script type="text/html" id="nameBar">
    {{#  if(d.packetId != undefined && d.packetId != null){ }}
    <div class="packetName">
        {{d.name}}
    </div>
    {{#  }else{ }}
    {{genGoodsName(d.name,d.norms)}}
    {{#  } }}
</script>


<script type="text/html" id="operBar">
    <a class="layui-btn layui-btn-xs layui-btn-danger table-operator" lay-event="delete">删除</a>
</script>
<script type="text/html" id="numberBar" >
    <div class="numberDiv">
        {{# if(d.sn==true){ }}
        <span class="number">{{ d.waitInNumber }}</span>
        <span class="numberSn">sn</span>
        {{# }else{ }}
        <input type="number" name="number" class="layui-input number" value="{{ d.waitInNumber }}" style="background: #ffffff">
        {{# } }}
    </div>
</script>

<script type="text/html" id="snNumberBar" >
    {{# if(d.sn==true){ }}
    <div class="snNumberDiv">0个</div>
    {{# } }}
</script>

<html:packetListDialog/>
<html:snListDialog/>
<html:loading/>
</html>